<?php
require_once("connect.php");

define('FACEBOOK_APP_ID', '248156948568489');
define('FACEBOOK_SECRET', '210774fa9540bd1e7f404de8197b1b55');

function parse_signed_request($signed_request, $secret) {
  list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

  // decode the data
  $sig = base64_url_decode($encoded_sig);
  $data = json_decode(base64_url_decode($payload), true);

  if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
    error_log('Unknown algorithm. Expected HMAC-SHA256');
    return null;
  }

  // check sig
  $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
  if ($sig !== $expected_sig) {
    error_log('Bad Signed JSON signature!');
    return null;
  }

  return $data;
}

function base64_url_decode($input) {
    return base64_decode(strtr($input, '-_', '+/'));
}

if ($_REQUEST) {
//  echo '<p>signed_request contents:</p>';
  $response = parse_signed_request($_REQUEST['signed_request'], FACEBOOK_SECRET);
  
  $name = $response['registration']['name'];
  $email = $response['registration']['email']; 
  $fbid = $response['user_id'];
  
  $res = mysql_query("SELECT * FROM site_early_invites WHERE `fbid`='$fbid'");
  if(mysql_numrows($res) != 0 ) {	$msg = "You've already registered pal! <a href='index.html'>Back</a>"; }
  else
  {  
  $result = mysql_query("INSERT INTO site_early_invites (`name`,`email`,`fbid`) VALUES ('$name','$email','$fbid')");
  if(!$result) echo mysql_error();
  $msg = "Thankyou for registering ".$name.". We'll keep you updated. <a href='index.html'>Back</a>";
  }
  	?>
	<html>
<head>
<style>
body
{
	background:#000;
	color:#b8b41f;
	text-shadow:0px 0px 10px #6a6837;
	font-family:arial;
	font-size:20pt;
}
</style>
</head>

<body>
<br><br>
<center>
<img src="logo.png"></img><br>
its coming soon folks<br> <span style="font-size:15pt">register here for an early invite<br><br>
<?php echo $msg; ?>
</span>
</center>
</body>
</html>
	<?php
    
} else {
  echo '$_REQUEST is empty';
}
?>